<?php
namespace app\admin\controller;
use think\Db;
class Model extends Common
{
    public function lst()
    {
    	$data=db('model')->order('id asc')->paginate(2);
    	$prefix=config('database.prefix');
    	$this->assign(array(
    		'data'=>$data,
    		'prefix'=>$prefix,
    		));
    	return view('list');
    }
    //ajax修改状态
    public function changestatus(){
      if(request()->isAjax()){
            $modelid=input('modelid');
            $status=db('model')->field('status')->where('id',$modelid)->find();
            $statusres=$status['status'];

            if($statusres ==1){
              db('model')->where('id',$modelid)->update(['status'=>0]);
              return 1;//有显示改为隐藏
            }else{
               db('model')->where('id',$modelid)->update(['status'=>1]);
              return 2;//有隐藏改为显示
            }
      }else{
           $this->error('非法操作！');
      }
	}

    public function add()
    {
    	if(request()->isPost()){
    		$data=input('post.');
            //验证器验证
            $validate = validate('Model');//助手函数
            if(!$validate->scene('add')->check($data)){
                $this->error($validate->getError());
            } 

    		$add=db('model')->insert($data);
    		if($add){
    			$name=$data['table_name'];
    			$tableName=config('database.prefix').$name;
    			$sql="create table {$tableName} (aid int unsigned not null) engine=MYISAM default charset=utf8";
    			Db::execute($sql);
    			$this->success('添加模型成功！',url('model/lst'));
    		}else{
    			$this->error('添加模型失败！');
    		}
    		return;
    	}
    	return view();
    }

    public function edit($id)
    {
    	$data=db('model')->find($id);
    	if(request()->isPost()){    
    		$table_name=$data['table_name'];
    		$input=input('post.');
            //验证器验证
            $validate = validate('Model');//助手函数
            if(!$validate->scene('edit')->check($input)){
                $this->error($validate->getError());
            } 
    		//表名修改
    		if($input['table_name'] !=$table_name){
    			$oldername=config('database.prefix').$table_name;//旧的表名
    			$tableName=config('database.prefix').$input['table_name'];//新的表名
    			$sql="alter table {$oldername} rename {$tableName} ";
    			Db::execute($sql);
    		}    		
    		$save=db('model')->where('id',$input['id'])->update($input);
    		if($save){
    			$this->success('修改模型成功！',url('model/lst'));
    		}else{
    			$this->error('修改模型失败！');
    		}
    	}
    	//dump($data);die;
    	$this->assign('data',$data);
    	return view();
    }

    //ajax异步删除模型
    public function del(){
    	if(request()->isAjax()){
    	$modelid=input('modelid');
    	$tableName=input('table_name');
    	 $del=db('model')->delete($modelid);
    	$sql="drop table {$tableName}";
    	$res=Db::execute($sql);//返回值是零
	    	if($del){
	    		echo 1;//删除模型和附加表成功！
	    	}else{
	    		echo 2;//删除模型和附加表成功！
	    	}
    	}
    }
}
